'use client';

import React, { useState, useEffect } from 'react';
import { 
  Table, 
  Card, 
  Tag, 
  Button, 
  Space, 
  Modal, 
  Form, 
  Select, 
  Input, 
  DatePicker, 
  message,
  Popconfirm,
  Row,
  Col,
  Statistic
} from 'antd';
import { 
  SearchOutlined, 
  EyeOutlined, 
  EditOutlined,
  SyncOutlined 
} from '@ant-design/icons';
import AdminLayout from '@/components/AdminLayout';
import { request } from '@/utils/request';

const { RangePicker } = DatePicker;
const { Option } = Select;

interface Order {
  id: number;
  orderNumber: string;
  userName: string;
  totalAmount: number;
  finalAmount: number;
  status: string;
  paymentMethod?: string;
  paymentTime?: string;
  recipientName: string;
  recipientPhone: string;
  shippingAddress: string;
  createdAt: string;
  updatedAt: string;
}

const AdminOrders: React.FC = () => {
  const [loading, setLoading] = useState(false);
  const [orders, setOrders] = useState<Order[]>([]);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
  });
  const [statusModalVisible, setStatusModalVisible] = useState(false);
  const [selectedOrder, setSelectedOrder] = useState<Order | null>(null);
  const [searchForm] = Form.useForm();
  const [statusForm] = Form.useForm();
  const [orderStats, setOrderStats] = useState<any>({});

  useEffect(() => {
    fetchOrders();
    fetchOrderStats();
  }, [pagination.current, pagination.pageSize]);

  const fetchOrders = async (searchParams?: any) => {
    try {
      setLoading(true);
      const params = {
        page: pagination.current,
        size: pagination.pageSize,
        ...searchParams,
      };

      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 1000));
      
      const mockOrders = [
        {
          id: 1,
          orderNumber: 'ORD20240101001',
          userName: '张三',
          totalAmount: 1299.00,
          finalAmount: 1199.00,
          status: 'PAID',
          paymentMethod: '支付宝',
          paymentTime: '2024-01-01 10:35:00',
          recipientName: '张三',
          recipientPhone: '13800138001',
          shippingAddress: '北京市朝阳区xxx路xxx号',
          createdAt: '2024-01-01 10:30:00',
          updatedAt: '2024-01-01 10:35:00'
        },
        {
          id: 2,
          orderNumber: 'ORD20240101002',
          userName: '李四',
          totalAmount: 2580.00,
          finalAmount: 2480.00,
          status: 'SHIPPED',
          paymentMethod: '微信支付',
          paymentTime: '2024-01-01 11:20:00',
          recipientName: '李四',
          recipientPhone: '13800138002',
          shippingAddress: '上海市浦东新区xxx路xxx号',
          createdAt: '2024-01-01 11:15:00',
          updatedAt: '2024-01-01 14:20:00'
        },
        {
          id: 3,
          orderNumber: 'ORD20240101003',
          userName: '王五',
          totalAmount: 899.00,
          finalAmount: 899.00,
          status: 'PENDING',
          recipientName: '王五',
          recipientPhone: '13800138003',
          shippingAddress: '广州市天河区xxx路xxx号',
          createdAt: '2024-01-01 12:20:00',
          updatedAt: '2024-01-01 12:20:00'
        }
      ];

      setOrders(mockOrders);
      setPagination(prev => ({ ...prev, total: 50 })); // 模拟总数

    } catch (error) {
      message.error('获取订单列表失败');
    } finally {
      setLoading(false);
    }
  };

  const fetchOrderStats = async () => {
    try {
      // 模拟订单统计数据
      setOrderStats({
        totalOrders: 156,
        pendingOrders: 23,
        paidOrders: 89,
        shippedOrders: 34,
        deliveredOrders: 8,
        cancelledOrders: 2
      });
    } catch (error) {
      console.error('获取订单统计失败:', error);
    }
  };

  const getStatusColor = (status: string) => {
    const colors: Record<string, string> = {
      'PENDING': 'orange',
      'PAID': 'blue',
      'SHIPPED': 'green',
      'DELIVERED': 'green',
      'CANCELLED': 'red'
    };
    return colors[status] || 'default';
  };

  const getStatusText = (status: string) => {
    const texts: Record<string, string> = {
      'PENDING': '待支付',
      'PAID': '已支付',
      'SHIPPED': '已发货',
      'DELIVERED': '已送达',
      'CANCELLED': '已取消'
    };
    return texts[status] || status;
  };

  const handleUpdateStatus = async (order: Order) => {
    setSelectedOrder(order);
    statusForm.setFieldsValue({
      status: order.status,
      trackingNumber: '',
      logisticsCompany: ''
    });
    setStatusModalVisible(true);
  };

  const handleStatusSubmit = async (values: any) => {
    try {
      // 调用更新订单状态API
      console.log('更新订单状态:', values);
      message.success('订单状态更新成功');
      setStatusModalVisible(false);
      fetchOrders();
    } catch (error) {
      message.error('更新订单状态失败');
    }
  };

  const handleSearch = (values: any) => {
    fetchOrders(values);
  };

  const handleReset = () => {
    searchForm.resetFields();
    fetchOrders();
  };

  const columns = [
    {
      title: '订单号',
      dataIndex: 'orderNumber',
      key: 'orderNumber',
      width: 180,
    },
    {
      title: '客户',
      dataIndex: 'userName',
      key: 'userName',
      width: 100,
    },
    {
      title: '金额',
      dataIndex: 'finalAmount',
      key: 'finalAmount',
      width: 120,
      render: (amount: number) => `¥${amount.toFixed(2)}`,
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (status: string) => (
        <Tag color={getStatusColor(status)}>
          {getStatusText(status)}
        </Tag>
      ),
    },
    {
      title: '支付方式',
      dataIndex: 'paymentMethod',
      key: 'paymentMethod',
      width: 100,
      render: (method: string) => method || '-',
    },
    {
      title: '收货人',
      dataIndex: 'recipientName',
      key: 'recipientName',
      width: 100,
    },
    {
      title: '创建时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
      width: 160,
    },
    {
      title: '操作',
      key: 'action',
      width: 200,
      render: (text: any, record: Order) => (
        <Space size="small">
          <Button 
            type="link" 
            size="small" 
            icon={<EyeOutlined />}
            onClick={() => {/* 查看订单详情 */}}
          >
            查看
          </Button>
          <Button 
            type="link" 
            size="small" 
            icon={<EditOutlined />}
            onClick={() => handleUpdateStatus(record)}
          >
            更新状态
          </Button>
        </Space>
      ),
    },
  ];

  return (
    <AdminLayout 
      selectedKey="4" 
      breadcrumbItems={[{ title: '订单管理' }]}
    >
      <div style={{ padding: '24px' }}>
        <h1 style={{ marginBottom: '24px', fontSize: '24px', fontWeight: 'bold' }}>
          订单管理
        </h1>

        {/* 订单统计 */}
        <Row gutter={[16, 16]} style={{ marginBottom: '24px' }}>
          <Col xs={12} sm={8} lg={4}>
            <Card>
              <Statistic
                title="总订单"
                value={orderStats.totalOrders || 0}
                valueStyle={{ color: '#1890ff' }}
              />
            </Card>
          </Col>
          <Col xs={12} sm={8} lg={4}>
            <Card>
              <Statistic
                title="待支付"
                value={orderStats.pendingOrders || 0}
                valueStyle={{ color: '#fa8c16' }}
              />
            </Card>
          </Col>
          <Col xs={12} sm={8} lg={4}>
            <Card>
              <Statistic
                title="已支付"
                value={orderStats.paidOrders || 0}
                valueStyle={{ color: '#52c41a' }}
              />
            </Card>
          </Col>
          <Col xs={12} sm={8} lg={4}>
            <Card>
              <Statistic
                title="已发货"
                value={orderStats.shippedOrders || 0}
                valueStyle={{ color: '#13c2c2' }}
              />
            </Card>
          </Col>
          <Col xs={12} sm={8} lg={4}>
            <Card>
              <Statistic
                title="已送达"
                value={orderStats.deliveredOrders || 0}
                valueStyle={{ color: '#722ed1' }}
              />
            </Card>
          </Col>
          <Col xs={12} sm={8} lg={4}>
            <Card>
              <Statistic
                title="已取消"
                value={orderStats.cancelledOrders || 0}
                valueStyle={{ color: '#f5222d' }}
              />
            </Card>
          </Col>
        </Row>

        {/* 搜索表单 */}
        <Card style={{ marginBottom: '24px' }}>
          <Form
            form={searchForm}
            layout="inline"
            onFinish={handleSearch}
          >
            <Form.Item name="orderNumber" label="订单号">
              <Input placeholder="请输入订单号" style={{ width: 200 }} />
            </Form.Item>
            <Form.Item name="userName" label="客户姓名">
              <Input placeholder="请输入客户姓名" style={{ width: 150 }} />
            </Form.Item>
            <Form.Item name="status" label="订单状态">
              <Select placeholder="请选择状态" style={{ width: 120 }} allowClear>
                <Option value="PENDING">待支付</Option>
                <Option value="PAID">已支付</Option>
                <Option value="SHIPPED">已发货</Option>
                <Option value="DELIVERED">已送达</Option>
                <Option value="CANCELLED">已取消</Option>
              </Select>
            </Form.Item>
            <Form.Item name="dateRange" label="创建时间">
              <RangePicker style={{ width: 300 }} />
            </Form.Item>
            <Form.Item>
              <Space>
                <Button type="primary" htmlType="submit" icon={<SearchOutlined />}>
                  搜索
                </Button>
                <Button onClick={handleReset}>
                  重置
                </Button>
                <Button 
                  icon={<SyncOutlined />} 
                  onClick={() => fetchOrders()}
                >
                  刷新
                </Button>
              </Space>
            </Form.Item>
          </Form>
        </Card>

        {/* 订单列表 */}
        <Card>
          <Table
            columns={columns}
            dataSource={orders}
            rowKey="id"
            loading={loading}
            pagination={{
              current: pagination.current,
              pageSize: pagination.pageSize,
              total: pagination.total,
              showSizeChanger: true,
              showQuickJumper: true,
              showTotal: (total, range) => 
                `第 ${range[0]}-${range[1]} 条/共 ${total} 条`,
              onChange: (page, pageSize) => {
                setPagination(prev => ({
                  ...prev,
                  current: page,
                  pageSize: pageSize || prev.pageSize,
                }));
              },
            }}
            scroll={{ x: 1200 }}
          />
        </Card>

        {/* 更新状态模态框 */}
        <Modal
          title="更新订单状态"
          open={statusModalVisible}
          onCancel={() => setStatusModalVisible(false)}
          onOk={() => statusForm.submit()}
          width={500}
        >
          <Form
            form={statusForm}
            layout="vertical"
            onFinish={handleStatusSubmit}
          >
            <Form.Item
              name="status"
              label="订单状态"
              rules={[{ required: true, message: '请选择订单状态' }]}
            >
              <Select placeholder="请选择状态">
                <Option value="PENDING">待支付</Option>
                <Option value="PAID">已支付</Option>
                <Option value="SHIPPED">已发货</Option>
                <Option value="DELIVERED">已送达</Option>
                <Option value="CANCELLED">已取消</Option>
              </Select>
            </Form.Item>
            <Form.Item
              name="logisticsCompany"
              label="物流公司"
            >
              <Input placeholder="请输入物流公司" />
            </Form.Item>
            <Form.Item
              name="trackingNumber"
              label="物流单号"
            >
              <Input placeholder="请输入物流单号" />
            </Form.Item>
          </Form>
        </Modal>
      </div>
    </AdminLayout>
  );
};

export default AdminOrders;